import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:kegelutils/bean/bean_day_event.dart';
import 'package:kegelutils/controller_events.dart';
import 'package:kegelutils/controller_main.dart';
import 'package:kegelutils/dailogs.dart';
import 'package:kegelutils/storage/get_storage_instance.dart';
import 'package:kegelutils/utils/calendar_event.dart';
import 'package:kegelutils/utils/utils_time.dart';
import 'package:table_calendar/table_calendar.dart';

final kToday = DateTime.now();
final kFirstDay = DateTime(kToday.year, kToday.month - 3, kToday.day);
final kLastDay = DateTime(kToday.year, kToday.month + 3, kToday.day);

int getHashCode(DateTime key) {
  return key.day * 1000000 + key.month * 10000 + key.year;
}

class CalendarPage extends StatefulWidget {
  const CalendarPage({Key? key}) : super(key: key);

  @override
  _CalendarPageState createState() => _CalendarPageState();
}

class _CalendarPageState extends State<CalendarPage> {
  CalendarFormat _calendarFormat = CalendarFormat.month;
  RangeSelectionMode _rangeSelectionMode = RangeSelectionMode.toggledOff;
  DateTime _focusedDay = DateTime.now();
  DateTime? _selectedDay;
  DateTime? _rangeStart;
  DateTime? _rangeEnd;

  //渐变效果设置
  late Gradient gradient;
  late Shader shader;

  @override
  void initState() {
    super.initState();

    gradient = const LinearGradient(
      begin: Alignment.centerLeft,
      end: Alignment.centerRight,
      colors: [
        Colors.red,
        Colors.purple,
      ],
    );
    shader = gradient.createShader(Rect.fromLTWH(
        0, 0, Get.mediaQuery.size.width, Get.mediaQuery.size.height));

    EventsController.to.monthEvents.value = MainController.getSaveEvents();
    EventsController.to.monthEvents.refresh();

    List<Event> todayEvents = [];
    for (Event event in EventsController.to.monthEvents) {
      if (isSameDay(DateTime.fromMillisecondsSinceEpoch(event.createTime!),
          DateTime.now())) {
        todayEvents.add(event);
      }
    }

    EventsController.to.todayEvents.value = todayEvents;
    EventsController.to.todayEvents.refresh();

    _selectedDay = _focusedDay;
  }

  @override
  Widget build(BuildContext context) {
    return Material(
      child: SafeArea(
        child: Container(
          padding: const EdgeInsets.symmetric(horizontal: 10.0),
          child: Column(
            children: [
              const SizedBox(height: 30.0),
              Stack(
                children: [
                  Align(
                    alignment: Alignment.center,
                    child: Text(
                      '训练记录',
                      style: TextStyle(
                        fontSize: 30.0,
                        fontWeight: FontWeight.bold,
                        foreground: Paint()..shader = shader,
                      ),
                    ),
                  ),
                  Align(
                    alignment: Alignment.centerLeft,
                    child: GestureDetector(
                      onTap: () {
                        Get.back();
                      },
                      child: Container(
                        width: 40,
                        height: 40,
                        decoration: BoxDecoration(
                          color: Colors.red,
                          borderRadius: BorderRadius.circular(50.0),
                        ),
                        child: const Center(
                          child: Icon(
                            Icons.arrow_back,
                            color: Colors.white,
                          ),
                        ),
                      ),
                    ),
                  ),
                  Align(
                    alignment: Alignment.centerRight,
                    child: GestureDetector(
                      onTap: () {
                        int addUpDuration = SpInstance.getInstance()
                            .getInt(KEY_ADD_UP_DURATION, defaultV: 0);
                        popDialog(
                            Center(
                              child: RichText(
                                text: TextSpan(
                                  text: '累计坚持锻炼  ',
                                  style: const TextStyle(
                                    fontSize: 18.0,
                                    color: Colors.black87,
                                  ),
                                  children: [
                                    TextSpan(
                                      text: '${addUpDuration ~/ 60}',
                                      style: TextStyle(
                                        fontWeight: FontWeight.bold,
                                        fontSize: 40.0,
                                        foreground: Paint()..shader = shader,
                                      ),
                                    ),
                                    const TextSpan(
                                      text: '  分钟。',
                                      style: TextStyle(
                                        fontSize: 18.0,
                                        color: Colors.black87,
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                            ), onPositiveTap: () {
                          Get.back();
                        });
                      },
                      child: Container(
                        width: 40,
                        height: 40,
                        decoration: BoxDecoration(
                          color: Colors.purple,
                          borderRadius: BorderRadius.circular(50.0),
                        ),
                        child: const Center(
                          child: Icon(
                            Icons.thumb_up_alt_outlined,
                            color: Colors.white,
                          ),
                        ),
                      ),
                    ),
                  ),
                ],
              ),
              const SizedBox(height: 20.0),
              TableCalendar<Event>(
                locale: 'zh_CN',
                firstDay: kFirstDay,
                lastDay: kLastDay,
                focusedDay: _focusedDay,
                selectedDayPredicate: (day) => isSameDay(_selectedDay, day),
                rangeStartDay: _rangeStart,
                rangeEndDay: _rangeEnd,
                calendarFormat: _calendarFormat,
                availableCalendarFormats: const {
                  CalendarFormat.month: '周',
                  CalendarFormat.twoWeeks: '月',
                  CalendarFormat.week: '2周',
                },
                rangeSelectionMode: _rangeSelectionMode,
                eventLoader: _getEventsForDay,
                startingDayOfWeek: StartingDayOfWeek.monday,
                calendarStyle: CalendarStyle(
                  // Use `CalendarStyle` to customize the UI
                  outsideDaysVisible: false,
                  markersMaxCount: 4,
                  markerDecoration: BoxDecoration(
                    color: Colors.red,
                    shape: BoxShape.circle,
                    border: Border.all(color: Colors.deepOrange, width: 1.0),
                  ),
                ),
                onDaySelected: _onDaySelected,
                onFormatChanged: (format) {
                  if (_calendarFormat != format) {
                    setState(() {
                      _calendarFormat = format;
                    });
                  }
                },
                onPageChanged: (focusedDay) {
                  _focusedDay = focusedDay;
                },
              ),
              Expanded(
                child: Obx(() {
                  List<Event> todayEvents =
                      EventsController.to.todayEvents.value;
                  todayEvents.sort((a, b) {
                    return b.createTime!.compareTo(a.createTime!);
                  });
                  todayEvents.forEach((element) {
                    print(element.toString());
                  });
                  return ListView.builder(
                    itemCount: todayEvents.length,
                    physics: const BouncingScrollPhysics(),
                    itemBuilder: (context, index) {
                      return buildPlanItem(todayEvents[index]);
                    },
                  );
                }),
              ),
            ],
          ),
        ),
      ),
    );
  }

  List<Event> _getEventsForDay(DateTime day) {
    List<Event> todayEvents = [];
    for (Event event in EventsController.to.monthEvents) {
      if (isSameDay(
          DateTime.fromMillisecondsSinceEpoch(event.createTime!), day)) {
        todayEvents.add(event);
      }
    }
    return todayEvents;
  }

  void _onDaySelected(DateTime selectedDay, DateTime focusedDay) {
    if (!isSameDay(_selectedDay, selectedDay)) {
      setState(() {
        _selectedDay = selectedDay;
        _focusedDay = focusedDay;
        _rangeStart = null; // Important to clean those
        _rangeEnd = null;
        _rangeSelectionMode = RangeSelectionMode.toggledOff;
      });

      EventsController.to.todayEvents.value = _getEventsForDay(selectedDay);
      EventsController.to.todayEvents.refresh();
    }
  }

  Widget buildPlanItem(Event event) {
    String durationStr = '${TimeUtils.formatMMFromSecond(event.duration!)}分钟';
    if (event.duration! < 60) {
      durationStr = '${event.duration!}秒钟';
    }
    return Container(
      margin: const EdgeInsets.symmetric(vertical: 5.0),
      padding: const EdgeInsets.symmetric(horizontal: 10.0, vertical: 10.0),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(5.0),
        gradient: const LinearGradient(
            colors: [Colors.red, Colors.purple],
            begin: Alignment.centerLeft,
            end: Alignment.centerRight),
      ),
      child: Column(
        children: [
          Container(
            alignment: Alignment.centerLeft,
            child: Text(
              MainController.buildPlanTitle(event.type!),
              style: const TextStyle(
                color: Colors.white,
                fontWeight: FontWeight.bold,
                fontSize: 20.0,
              ),
            ),
          ),
          SizedBox(height: 10.0),
          Container(
            alignment: Alignment.centerLeft,
            child: Text(
              '${TimeUtils.formatYYMMDDHHMM(event.createTime!)} 完成，训练时长$durationStr',
              style: TextStyle(
                color: Colors.white,
                fontSize: 14.0,
              ),
            ),
          ),
        ],
      ),
    );
  }
}
